package git.soulbgm.jd;

import git.soulbgm.utils.PropertiesUtil;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * jd应用程序
 *
 * @author SoulBGM
 * @date 2021/07/02
 */
public class JdApplication {

    private static WebDriver driver;
    private static ChromeOptions options;
    private static String passportJdUrl = "https://plogin.m.jd.com/login/login";
    private static String phone = "15535483998";
    //log.gif
    private static final Pattern[] patternArray = {Pattern.compile("pt_key=.+?;"), Pattern.compile("pt_pin=.+?;")};

    /**
     * 判断运行时是否是以jar运行
     *
     * @return boolean
     */
    private static boolean isJar(String path) {
        File file = new File(path);
        return file.isFile();
    }

    /**
     * 检测环境
     */
    private static void detectionEnvironment() throws IOException {
        String path = JdApplication.class.getProtectionDomain().getCodeSource().getLocation().getPath();
        String configFilePath = "config.properties";
        if (isJar(path)) {
            path = path.substring(0, path.lastIndexOf(PropertiesUtil.LEFT_SLANTING_BAR));
            configFilePath = path + File.separator + "config.properties";
        }
        Map<String, String> config = PropertiesUtil.getPrefixProperties(configFilePath, "config", "#");
        System.setProperty("webdriver.chrome.driver", config.get("chromeDriverPath"));
    }

    public static void main(String[] args) throws IOException, InterruptedException {
        detectionEnvironment();
        options = new ChromeOptions();
        options.addArguments("--mute-audio");
        options.addArguments("--hide-scrollbars");
        options.addArguments("disable-infobars");

        driver = new ChromeDriver(options);
        getCookies();
    }

    /**
     * 获取cookies
     *
     * @throws InterruptedException 中断异常
     */
    private static void getCookies() throws InterruptedException {
        driver.get(passportJdUrl);
        driver.findElement(By.className("mobile")).sendKeys(phone);
        driver.findElement(By.className("getMsg-btn")).click();
        Scanner scanner = new Scanner(System.in);
        String result = scanner.nextLine();
        StringBuilder cookieValue = new StringBuilder();
        for (Pattern pattern : patternArray) {
            Matcher matcher = pattern.matcher(result);
            if (matcher.find()) {
                cookieValue.append(matcher.group(0));
            }
        }
        System.out.println(cookieValue);
        Thread.sleep(100);
        driver.close();
    }

}
